package com.hkts.naturalgasauthentication.security.jwt;

import cn.hutool.core.util.StrUtil;
import com.hkts.naturalgasauthentication.common.Exception.BlankException;
import com.hkts.naturalgasauthentication.common.Exception.CodeIsErrorException;
import com.hkts.naturalgasauthentication.common.Exception.CodeIsNullException;
import com.hkts.naturalgasauthentication.common.Exception.LoginFailLimitException;
import com.hkts.naturalgasauthentication.config.properties.ManagementTokenProperties;
import com.hkts.naturalgasauthentication.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class AuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ManagementTokenProperties tokenProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        if (e instanceof BlankException) {
            Map<String, Object> resultMap = new HashMap<String, Object>(16);
            resultMap.put("message", "error");
            resultMap.put("code", 501);
            resultMap.put("timestamp", System.currentTimeMillis());
            resultMap.put("result", "您已经被拉黑！");
            ResponseUtil.out(response, resultMap);
        }
        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            String userName = request.getParameter("userName");
            recordLoginTime(userName);
            String key = "loginTimeLimit:" + userName;
            String value = redisTemplate.opsForValue().get(key);
            if (StrUtil.isBlank(value)) {
                value = "0";
            }
            int loginFailTime = Integer.parseInt(value);
            int restLoginTime = tokenProperties.getLoginTimeLimit() - loginFailTime;
            log.info("用户" + userName + "登录失败，还有" + restLoginTime + "次机会");
            if (restLoginTime <= 3 && restLoginTime > 0) {
                ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "用户名或密码错误，还有" + restLoginTime + "次尝试机会"));
            } else if (restLoginTime <= 0) {
                ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "登录错误次数超过限制，请" + tokenProperties.getLoginAfterTime() + "分钟后再试"));
            } else {
                ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "用户名或密码错误"));
            }
        }
        if (e instanceof LoginFailLimitException) {
            ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, ((LoginFailLimitException) e).getMsg()));
        }
        if (e instanceof CodeIsNullException) {
            ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "验证码过期，请点击重发！"));
        }
        if (e instanceof CodeIsErrorException) {
            ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "验证码错误，请修改后重新提交！"));
        }
        if (e instanceof InternalAuthenticationServiceException) {
            ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "该手机号还未注册，请注册后再登录！"));
        } else {
            e.printStackTrace();
            ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "登陆失败，该用户已被封禁，请联系管理员解封。"));
        }
    }
    /**
     * 判断用户登陆错误次数
     */
    public boolean recordLoginTime(String username){

        String key = "loginTimeLimit:"+username;
        String flagKey = "loginFailFlag:"+username;
        String value = redisTemplate.opsForValue().get(key);
        if(StrUtil.isBlank(value)){
            value = "0";
        }
        //获取已登录错误次数
        int loginFailTime = Integer.parseInt(value) + 1;
        redisTemplate.opsForValue().set(key, String.valueOf(loginFailTime), tokenProperties.getLoginAfterTime(), TimeUnit.MINUTES);
        if(loginFailTime>=tokenProperties.getLoginTimeLimit()){
            redisTemplate.opsForValue().set(flagKey, "fail", tokenProperties.getLoginAfterTime(), TimeUnit.MINUTES);
            return false;
        }
        return true;
    }
}
